import nodemailer from 'nodemailer'

export type SendMailResult = { ok: boolean; info?: any; error?: any }

// 默认使用环境变量，提供了一个可编辑的示例默认值（强烈建议在生产中使用环境变量而不是把密码写入代码）
const SMTP_CONFIG = {
  host: process.env.SMTP_HOST || 'smtp.163.com',
  port: process.env.SMTP_PORT ? Number(process.env.SMTP_PORT) : 465,
  secure: process.env.SMTP_SECURE ? process.env.SMTP_SECURE === 'true' : true,
  auth: {
    user: process.env.SMTP_USER ,
    pass: process.env.SMTP_PASS 
  }
}

let transporter: nodemailer.Transporter | null = null

function getTransporter() {
  if (transporter) return transporter
  transporter = nodemailer.createTransport({
    host: SMTP_CONFIG.host,
    port: SMTP_CONFIG.port,
    secure: SMTP_CONFIG.secure,
    auth: SMTP_CONFIG.auth
  })
  return transporter
}

export async function sendMail(to: string, subject: string, html?: string, text?: string): Promise<SendMailResult> {
  try {
    const t = getTransporter()
    const mailOptions = {
      from: SMTP_CONFIG.auth.user,
      to,
      subject,
      text: text || undefined,
      html: html || undefined
    }

    const info = await t.sendMail(mailOptions)
    return { ok: true, info }
  } catch (error) {
    return { ok: false, error }
  }
}

export default { sendMail }
